<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html" ; charset="utf-8" />
    <title>宏宇教育信息采集</title>
    <link href="./index.css" rel="stylesheet" type="text/css" />
  </head>

  <style>
    .hide .el-upload--picture-card {
      display: none;
    }
    .box-card {
      margin: 20px 0;
    }
    
  </style>

  <body>
    <div id="app">
      <app-refund-base-information
        type="look"
        ref="baseInfo"
      ></app-refund-base-information>
      <app-education
        type="look"
        :level-list="levelList"
        v-if="isEducation"
        ref="education"
      ></app-education>
      <app-occupation
        type="look"
        v-if="isOccupation"
        ref="occupation"
      ></app-occupation>
      <app-title
        type="look"
        v-if="isTitle"
        ref="title"
      ></app-title>
      <app-train
        type="look"
        v-if="isTrain"
        ref="train"
      ></app-train>
      <app-cost-information
        type="look"
        :fee-len="feeLen"
        ref="costInfo"
        :title="costTitle"
      ></app-cost-information>
      <app-refund-info :type="type" ref="refundInfo"></app-refund-info>
      <el-row>
        <el-col style="display: flex; justify-content: center">
          <el-button :disabled="isSubmit" type="primary" @click="handleValid('submit')">提交</el-button>
        </el-col>
      </el-row>
    </div>

    <script src="../../../js/jquery.js"></script>
    <script src="../../../js/common.js"></script>
    <script src="../../../js/vue.js"></script>
    <script src="../../../js/element.js"></script>
    <script src="./components/RefundBaseInfo.js"></script>
    <script src="./components/EducationLevel.js"></script>
    <script src="./components/Certificate.js"></script>
    <script src="./components/Education.js"></script>
    <script src="./components/Occupation.js"></script>
    <script src="./components/Title.js"></script>
    <script src="./components/Train.js"></script>
    <script src="./components/CostInformation.js"></script>
    <script src="./components/RefundInfo.js"></script>

    <script>
      const app = new Vue({
        el: "#app",
        created() {
          this.infoName = getQuery('trainType');
        },
        mounted() {
          this.getPageTitle();
          this.getEducationOption();
          // 如果是通过操作进入当前页面，就调用获取的接口

          (this.type = getQuery("type")) && this.getStudentInfo();
        },
        data: {
          isSubmit: false,
          levelList: [],
          // 当前页面的名称
          infoName: '',
          id: "",
          genId: "",
          type: "",
          action: "",
          idNo: "",
          refundData: null,
          feeLen: 1,
          studyId: "",
          baseInfoMap: new Map([
            ["name", "name"],
            ["phoneNum", "phone"],
            ["idNo", "idNum"],
            ["sex", "gender"],
          ]),
          educationMap: new Map([
            ["studyMode", "pathLabel"],
            ["educationName", "levelLabel"],
            ["schoolName", "schoolLabel"],
            ["majorName", "discipline"],
            ["batch", "batch"],
          ]),
          occupationKeys: [
            'professionalTypes',
            'majorName',
            'batch',
            'applyExplain',
          ],
          titleKeys: [
            'professionalLevel',
            'professionalSeries',
            'majorName',
            'batch',
          ],
          trainKeys: [
            'applyProject',
            'examCourse',
            'classs',
            'applyAssist',
            'startDate',
            'endDate',
            'batch',
          ],
          feesMap: new Map([
            ["stage", "stage"],
            ["amount", "fee"],
            ["term", "feeDate"],
            ["flag", "isFee"],
            ["receiptStatus", "receipt"],
            ["receiptNo", "receiptNum"],
          ]),
          feeMap: new Map([
            ["otherFee", "otherFee"],
            ["paidinFee", "training"],
            ["explains", "description"],
            ["allFee", "total"],
            ["preferentialFee", "discount"],
            ["realPayFee", "paid"],
          ]),
        },
        computed: {
          isEducation() {
            return this.infoName === 'education';
          },
          isOccupation() {
            return this.infoName === 'occupation';
          },
          isTitle() {
            return this.infoName === 'title';
          },
          isTrain() {
            return this.infoName === 'train';
          },
          costTitle() {
            const map = {
              'education': '学历',
              'occupation': '职业',
              'title': '职称',
              'train': '培训'
            };
            return map[this.infoName];
          },
        },
        methods: {
          getPageTitle() {
            const type = getQuery('from');
            switch (type) {
                case 'student':
                    localStorage.setItem('name', '学生管理/学生信息查询/退款');
                    break;
                case 'jiaowu':
                    localStorage.setItem('name', '教务管理/教务信息管理/审核');
                    break;
                case 'jiaofei':
                    localStorage.setItem('name', '财务管理/缴费信息管理/审核')
                    break;
                case 'fenqi':
                    localStorage.setItem('name', '学生管理/分期缴费信息查询/退款')
                    break;
            }
          },
          getRefs(key = "") {
            const {
              baseInfo = {},
              costInfo = {},
              refundInfo = {},
              education = {},
              occupation = {},
              title = {},
              train = {},
            } = this.$refs;

            return {
              baseInfo: baseInfo[key],
              costInfo: costInfo[key],
              refundInfo: refundInfo[key],
              education: education[key],
              occupation: occupation[key],
              title: title[key],
              train: train[key],
            };
          },
          handleValid(flag) {
            this.action = flag;
            this.$refs.refundInfo.$refs.form.validate((valid) => {
              if (valid) {
                this.submit();
              } else {
                this.$message({
                  message: '退款信息未填写完成',
                  type: "error",
                });
              }
            });
          },
          submit() {
            const from = getQuery('from');
            const type = getQuery('type');
            const { refundInfo } = this.getRefs("formData");
            const { student, fees, studentCards, studentEducation = null, studentOccupation = null, studentTitle = null, studentTrain = null } = this.refundData;

            delete student.createDate;
            studentCards.map(item => delete item.createDate);
            if (studentEducation) {
              delete studentEducation.createDate
            } else if (studentOccupation) {
              delete studentOccupation.createDate
            } else if (studentTitle) {
              delete studentTitle.createDate
            } else {
              delete studentTrain.createDate
            }

            student.denyReason = '';
            fees.map((item) => {
              item.commitFlag = from === 'student' ? 4 : 1;
              item.businessProgress = from === 'student' ? 1 : 2;
              item.refundableFee = refundInfo.refundableFee;
              item.deductFee = refundInfo.deductFee;
              item.realRefundFee = refundInfo.realRefundFee;
              item.performanceFlag = +refundInfo.performanceFlag;
              item.refundInfo = refundInfo.refundInfo;
              item.payee = refundInfo.payee;
              delete item.createDate;
            });

            $.ajax({
              url: baseUrl + "studentInfo/updateStudentInfo",
              method: "Post",
              contentType: "application/json;charset=UTF-8",
              data: JSON.stringify({
                ...this.refundData, 
              }),
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo")).token,
              },
              success: (data) => {
                  this.isSubmit = true;
                  this.postFees(data, fees);
              },
              error: (err, res, res1) => {
                this.$message({
                  message: err.responseJSON.message || "网络错误",
                  type: "error",
                });
              },
            });
          },
          postFees({ commitBoolean }, fees) {
            fees.map((item) => {
              if (!item.commitBoolean) {
                item.commitBoolean = commitBoolean
              }
              delete item.createDate
            });

            $.ajax({
              url: baseUrl + "studentInfo/updateStudentFees",
              method: "post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo")).token,
              },
              contentType: "application/json",
              data: JSON.stringify(fees),
              success: (data) => {
                this.$message({
                  message: `${this.action === 'save' ? '保存成功' : '提交成功'}`,
                  type: "success",
                });
                switch (getQuery('from')) {
                  case 'student': 
                        window.location.href = '../hotel/studentSearch.html';
                        break;
                  case 'caiwu': 
                        window.location.href = '../store/moneySearch.html';
                        break;
                  case 'jiaowu': 
                        window.location.href = '../trade/tradeSearch.html';
                        break;
                }
              },
            });
          },
          getStudentInfo() {
            const trainType = getQuery("trainType");
            const idNo = getQuery("idNo");
            const studyId = getQuery("studyId");

            const {
              baseInfo,
              costInfo,
              refundInfo,
              education,
              occupation,
              title,
              train,
            } = this.getRefs("formData");

            $.ajax({
              url: baseUrl + "studentInfo/getStudentInfo",
              method: "get",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              data: {
                idNo,
                trainType,
                studyId,
              },
              success: (data) => {
                this.refundData = data;
                this.feeLen = data.fees.length;
                for (item of this.baseInfoMap) {
                  baseInfo[item[1]] = data.student[item[0]];
                }

                if (education) {
                  for (item of this.educationMap) {
                    this.type === 'edit' && (this.genId = data.studentEducation.id)
                    education[item[1]] = data.studentEducation[item[0]]
                  }
                }

                if (occupation) {
                  for (item of this.occupationKeys) {
                    this.type === 'edit' && (this.genId = data.studentOccupation.id)
                    occupation[item] = data.studentOccupation[item];
                  }
                }

                if (title) {
                  for (item of this.titleKeys) {
                    this.type === 'edit' && (this.genId = data.studentTitle.id)
                    title[item] = data.studentTitle[item];
                  }
                }

                if (train) {
                  for (item of this.trainKeys) {
                    this.type === 'edit' && (this.genId = data.studentTrain.id)
                    if (item === 'examCourse') {
                      (train[item] = data.studentTrain[item].split(','));
                    } else {
                      (train[item] = data.studentTrain[item]);
                    }
                  }
                }

                data.fees.map((feeItem, index) => {
                  refundInfo && (refundInfo.refundableFee = feeItem.realPayFee)
                  refundInfo && (refundInfo.deductFee = feeItem.deductFee)
                  refundInfo && (refundInfo.realRefundFee = feeItem.realRefundFee)
                  const performanceFlag = +feeItem.performanceFlag ? +feeItem.performanceFlag : ''
                  refundInfo && (refundInfo.performanceFlag = performanceFlag)
                  refundInfo && (refundInfo.refundInfo = feeItem.refundInfo)
                  refundInfo && (refundInfo.payee = feeItem.payee)
                  costInfo.otherName = feeItem.otherName;
                  for (item of this.feeMap) {
                    costInfo[item[1]] = feeItem[item[0]];
                  }
                  for (feesItem of this.feesMap) {
                    this.type === 'edit' && (costInfo.fees[index].id = feeItem.id)
                    if (['stage', 'fee'].includes(feesItem[1])) {
                      costInfo.fees[index][feesItem[1]] = feeItem[feesItem[0]] || undefined;
                    } else {
                      costInfo.fees[index][feesItem[1]] = feeItem[feesItem[0]];
                    }
                  }
                });
              },
            });
          },
          getEducationOption() {
            $.ajax({
              url: baseUrl + "education/queryEducationList",
              async: false,
              method: "Post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              success: (data) => {
                this.levelList = data;
              },
            });
          },
        },
      });
    </script>
  </body>
</html>
